<?php

namespace app\common\model;

use app\api\controller\Funds;
use think\Db;
use think\Exception;
use think\Model;

class RebateRecord extends Model
{
    // 表名
    protected $name = 'rebate_record';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    // 追加属性
    protected $append = [
        'status_text',
	    'type_text',
        'create_time_text',
        'update_time_text',
        'rebate_time_text',
    ];
    
	const STATUS_W = 0;
	const STATUS_Y = 1;
	const STATUS_C = 2;
	
	public static $_status = [
		self::STATUS_W => '待返利',
		self::STATUS_Y => '已返利',
		self::STATUS_C => '已取消',
	];
	
	
	const TYPE_SHOP = 1;
	const TYPE_TBK = 2;
	const TYPE_JD = 3;
	const TYPE_PDD = 4;
	
	public static $typeList = [
		self::TYPE_SHOP => '商城',
		self::TYPE_TBK => '淘宝',
		self::TYPE_JD => '京东',
		self::TYPE_PDD => '拼多多'
	];
    
    public function getStatusList()
    {
    	return self::$_status;
    }

    
    public function getTypeTextAttr($value, $data) {
    	$value = $value ? $value : $data['type'];
    	$list = self::$typeList;
    	return isset($list[$value]) ? $list[$value] : '';
    }

    public function getStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    
    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['update_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getRebateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['rebate_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setRebateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
	
	public function user() {
		return $this->belongsTo('User', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function order() {
		return $this->belongsTo('Order', 'order_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function ordergoods() {
		return $this->belongsTo('OrderGoods', 'order_goods_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	/**
	 * 添加返利记录
	 * @param $amount 返利金额
	 * @param $userId 用户
	 * @param $orderId 订单ID
	 * @param $type 返利类型
	 * @param $rebateRule 返利规则
	 * @param $goodsId 商品ID
	 * @param string $remark 备注
	 */
	public function addRecord($amount, $userId, $orderId, $type, $rebateRule, $goodsId , $remark = ''){
    	$data = [
    		'user_id' => $userId,
		    'order_id' => $orderId,
		    'order_goods_id' => $goodsId,
		    'amount' => $amount,
		    'remark' => $remark,
		    'type' => $type,
		    'rule_remark' => $rebateRule,
		    'create_time' => time(),
		    'update_time' => time()
	    ];
    	
    	$res = Db::name('rebateRecord')->insertGetId($data);
    	return $res;
	}
	
	/**
	 * 实际返利
	 * @param $orderid
	 * @param $type
	 * @return bool
	 * @throws Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function rebate($orderid, $type) {
		//查找这个订单的待返利记录
		$rows = Db::name('rebateRecord')
			->where(['order_id' => $orderid, 'type' => $type, 'status' => self::STATUS_W])
			->field('id, user_id, amount')
			->select();
		if(!$rows) {
			return true;
		}
		
		$fundsModle = new FundsRecord();
		foreach($rows as $row) {
			$res = Db::name('rebateRecord')
				->where(['id' => $row['id']])
				->update(['status' => self::STATUS_Y, 'update_time' => time()]);
			if(!$res) {
				$this->error = '更改返利记录【'.$row['id'].'】状态出错';
				return false;
			}
			
			$user = Db::name('user')->find($row['user_id']);
			//用户加钱
			
			$userRes = Db::name('user')->where(['id' => $row['user_id']])->setInc('balance', $row['amount']);
			if(!$userRes) {
				$this->error = '添加用户【'.$row['user_id'].'】金额出错';
				return false;
			}
			
			$fundsRes = $fundsModle->addRecord($row['user_id'], $row['amount'], $user['balance'], $fundsModle::ACCOUNT_TYPE_BALANCE, $fundsModle::OPE_TYPE_PLUS, $fundsModle::TYPE_VOUCHER_REBATE, $orderid);
			if(!$fundsRes) {
				throw new Exception('添加用户【'.$row['user_id'].'】资金记录出错');
				return false;
			}
			
		}
		return true;
	}
}


